package controller;

import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import paper.PubMedDB;
import entity.Protein;
import util.CommonUtil;
import util.FileUtil;
import util.LoopBody;
import util.Parallel;
import util.UniprotParserUtil;
import util.UniprotXML;

public class Test {

	public static void main(String[] args) throws InterruptedException {
		String[] inputFilePaths = {
				"proteins/test.txt"
		};
		for (String filePath: inputFilePaths) {
			FindMutationPapers(filePath);
		}
		
	}
	
	public static void FindMutationPapers(String inputFilePath) throws InterruptedException {
		String fileName = CommonUtil.getFileNameWithoutExtension(inputFilePath);
		String fileContents = FileUtil.getFileContents(inputFilePath);
		List<Protein> proteins = UniprotParserUtil.parseSearchResults(fileContents);

		final UniprotXML uni = new UniprotXML();

		PubMedDB pubmed = new PubMedDB();
		String filesFolder = "files/";
		if(!FileUtil.pathExists(filesFolder)) {
			FileUtil.createDirectory(filesFolder);
		}
		final ReentrantReadWriteLock lock= new ReentrantReadWriteLock();
		final Lock readLock = lock.readLock();
	    final Lock  writeLock = lock.writeLock();
//		for (Protein p: proteins) {
		Parallel.<Protein>ForEach(proteins, 
			new LoopBody<Protein>()
			{
				public void run(Protein p)
				{
					
				    writeLock.lock();
					try 
					{
						System.out.println(p.getEntry()+"=========");
						uni.downloadXMLfromUniprot(p.getEntry());
						
						System.out.println("Mutations");
						Set<String> pubMedIDsMutations = uni.getPubMedIdsForMutations(p.getEntry());
						for(String id : pubMedIDsMutations) {
							System.out.println(id);}
					}
						catch (Exception e) {
						e.printStackTrace();
					}
					finally{writeLock.unlock();}					
				}
			}
		);			
	}
}
